﻿using FreeSql.DatabaseModel;
using RazorEngine;
using RazorEngine.Configuration;
using RazorEngine.Templating;
using RazorEngine.Text;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace FreeSqlTools.Common
{
    public class CodeGenerate
    {
        /// <summary>
        /// 传入任务信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
        {
            try
            {
                var paths = await Task.Run(() =>
                {
                    var config = new TemplateServiceConfiguration();
                    config.EncodedStringFactory = new RawStringFactory();
                    Engine.Razor = RazorEngineService.Create(config);

                    string path = string.Empty;


                    foreach (var templatesPath in taskBuild.Templates)
                    {
                        path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                        var razorId = Guid.NewGuid().ToString("N");
                        var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
                        Engine.Razor.Compile(html, razorId);
                        //开始生成操作
                        foreach (var table in outputTables)
                        {
                            var sw = new StringWriter();
                            var model = new RazorModel(taskBuild, outputTables, table);
                            Engine.Razor.Run(razorId, sw, null, model);
                            StringBuilder plus = new StringBuilder();
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.AppendLine("// <auto-generated>");
                            plus.AppendLine("//     此代码由工具生成。");
                            plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                            plus.AppendLine("//     Website: http://www.freesql.net");
                            plus.AppendLine("//     对此文件的更改可能会导致不正确的行为，并且如果");
                            plus.AppendLine("//     重新生成代码，这些更改将会丢失。");
                            plus.AppendLine("// </auto-generated>");
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.Append(sw.ToString());
                            plus.AppendLine();
                            var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
                            if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
                                outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
                            File.WriteAllText(outPath, plus.ToString());
                        }
                    }
                    return path;
                });
                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                return "生成时发生异常,请检查模版代码.";
            }


        }

        public async Task<string> Setup(TaskBuild taskBuild, string code, List<DbTableInfo> dbTables, DbTableInfo dbTableInfo)
        {
            StringBuilder plus = new StringBuilder();
            try
            {
                var config = new TemplateServiceConfiguration();
                config.EncodedStringFactory = new RawStringFactory();
                Engine.Razor = RazorEngineService.Create(config);
                var razorId = Guid.NewGuid().ToString("N");
                Engine.Razor.Compile(code, razorId);

                var sw = new StringWriter();
                var model = new RazorModel(taskBuild, dbTables, dbTableInfo);
                Engine.Razor.Run(razorId, sw, null, model);

                plus.AppendLine("//------------------------------------------------------------------------------");
                plus.AppendLine("// <auto-generated>");
                plus.AppendLine("//     此代码由工具生成。");
                plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                plus.AppendLine("//     Website: http://www.freesql.net");
                plus.AppendLine("//     对此文件的更改可能会导致不正确的行为，并且如果");
                plus.AppendLine("//     重新生成代码，这些更改将会丢失。");
                plus.AppendLine("// </auto-generated>");
                plus.AppendLine("//------------------------------------------------------------------------------");
                plus.Append(sw.ToString());
                plus.AppendLine();
                return await Task.FromResult(plus.ToString());
            }
            catch
            {
                return await Task.FromResult(plus.ToString());
            }
        }
    }
}
